<?php
/**
 * User: YL
 * Date: 2019/6/10
 */

namespace app\common\middleware;

use Closure;
use restful\utils\Env;
use think\Request;

class First
{
    protected $filterFields = ['s', 'field', 'where'];

    public function handle(Request $request, Closure $next)
    {
        // 初始化环境变量
        Env::getInstance();

        // 设置运行环境变量
        $_ENV['runtime_prefix'] = $request->rule()->getOption('prefix', '');
        $_ENV['runtime_module'] = $request->rule()->getOption('module', '');
        $_ENV['runtime_controller'] = $request->rule()->getOption('controller', '');
        $_ENV['runtime_method'] = $request->rule()->getOption('method', '');

        // 设置运行参数
        $params = json_decode($request->param('params', ''), true);
        if (! empty($params)) {
            $request->runParams = $params;
        } else {
            $request->runParams = $request->except($this->filterFields);
        }

        return $next($request);
    }
}